/* -*- P4_16 -*- */
#include <core.p4>
#include <v1model.p4>

const bit<16> TYPE_IPV4 = 0x0800;
const bit<16> TYPE_IPV6 = 0x86DD;
const bit<16> TYPE_SR   = 0x0908;

/*************************************************************************
************************ HEADERS ******************************************
*************************************************************************/

typedef bit<9>  egressSpec_t;
typedef bit<48> macAddr_t;
typedef bit<32> ip4Addr_t;
typedef bit<8>  port_t;

header ethernet_t {
    macAddr_t dstAddr;
    macAddr_t srcAddr;
    bit<16>   etherType;
}

header ipv4_t {
    bit<4>    version;
    bit<4>    ihl;
    bit<8>    diffserv;
    bit<16>   totalLen;
    bit<16>   identification;
    bit<3>    flags;
    bit<13>   fragOffset;
    bit<8>    ttl;
    bit<8>    protocol;
    bit<16>   hdrChecksum;
    ip4Addr_t srcAddr;
    ip4Addr_t dstAddr;
}

header ipv6_t {
    bit<4>  version;
    bit<8>  trafficClass;
    bit<20> flowLabel;
    bit<16> payLoadLen;
    bit<8>  nextHdr;
    bit<8>  hopLimit;
    bit<128> srcAddr;
    bit<128> dstAddr;
}

header source_routing_t {
    bit<8>  path_len;
    bit<8>  current_index;
    port_t  port0;
    port_t  port1;
    port_t  port2;
    port_t  port3;
}

/*************************************************************************
************************ METADATA *****************************************
*************************************************************************/

struct metadata {
    // 已移除 current_index
}

struct headers {
    ethernet_t ethernet;
    ipv4_t     ipv4;
    ipv6_t     ipv6;
    source_routing_t sr;
}

/*************************************************************************
************************ PARSER *******************************************
*************************************************************************/

parser MyParser(packet_in packet,
                out headers hdr,
                inout metadata meta,
                inout standard_metadata_t standard_metadata) {

    state start {
        transition parse_ethernet;
    }

    state parse_ethernet {
        packet.extract(hdr.ethernet);
        transition select(hdr.ethernet.etherType) {
            TYPE_IPV4: parse_ipv4;
            TYPE_IPV6: parse_ipv6;
            TYPE_SR:   parse_sr;
            default: accept;
        }
    }

    state parse_ipv4 {
        packet.extract(hdr.ipv4);
        transition accept;
    }

    state parse_ipv6 {
        packet.extract(hdr.ipv6);
        transition accept;
    }

    state parse_sr {
        packet.extract(hdr.sr); // 现在会提取 current_index
        transition accept;
    }
}

/*************************************************************************
******************* CHECKSUM VERIFICATION ********************************
*************************************************************************/

control MyVerifyChecksum(inout headers hdr, inout metadata meta) {
    apply { }
}

/*************************************************************************
******************* INGRESS PROCESSING ***********************************
*************************************************************************/

control MyIngress(inout headers hdr,
                  inout metadata meta,
                  inout standard_metadata_t standard_metadata) {

    action drop() {
        mark_to_drop(standard_metadata);
    }

    action ipv4_forward(macAddr_t dstAddr, egressSpec_t port) {
        standard_metadata.egress_spec = port;
        hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
        hdr.ethernet.dstAddr = dstAddr;
        hdr.ipv4.ttl = hdr.ipv4.ttl - 1;
    }

    action ipv6_forward(macAddr_t dstAddr, egressSpec_t port) {
        standard_metadata.egress_spec = port;
        hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
        hdr.ethernet.dstAddr = dstAddr;
        hdr.ipv6.hopLimit = hdr.ipv6.hopLimit - 1;
    }

    // 源路由转发动作（修改后）
    action source_route_forward_0() {
        standard_metadata.egress_spec = (bit<9>)hdr.sr.port0;
        hdr.sr.current_index = hdr.sr.current_index + 1; // 更新包头索引
    }
    action source_route_forward_1() {
        standard_metadata.egress_spec = (bit<9>)hdr.sr.port1;
        hdr.sr.current_index = hdr.sr.current_index + 1;
    }
    action source_route_forward_2() {
        standard_metadata.egress_spec = (bit<9>)hdr.sr.port2;
        hdr.sr.current_index = hdr.sr.current_index + 1;
    }
    action source_route_forward_3() {
        standard_metadata.egress_spec = (bit<9>)hdr.sr.port3;
        hdr.sr.current_index = hdr.sr.current_index + 1;
    }

    table ipv4_lpm {
        key = {
            hdr.ipv4.dstAddr: lpm;
        }
        actions = {
            ipv4_forward;
            drop;
            NoAction;
        }
        size = 1024;
        default_action = drop();
    }

    table ipv6_lpm {
        key = {
            hdr.ipv6.dstAddr: lpm;
        }
        actions = {
            ipv6_forward;
            drop;
            NoAction;
        }
        size = 1024;
        default_action = drop();
    }

    table sr_table {
        key = {
            hdr.sr.current_index : exact; // 关键修改：匹配包头索引
        }
        actions = {
            source_route_forward_0;
            source_route_forward_1;
            source_route_forward_2;
            source_route_forward_3;
            drop;
            NoAction;
        }
        size = 4;
        default_action = drop();
    }

    apply {
        // 初始化源路由索引（仅首跳处理）
        if (standard_metadata.ingress_port == 0 && hdr.sr.isValid()) {
            hdr.sr.current_index = 0;
        }

        if (hdr.ipv4.isValid()) {
            ipv4_lpm.apply();
        } else if (hdr.ipv6.isValid()) {
            ipv6_lpm.apply();
        } else if (hdr.sr.isValid()) {
            // 有效性检查
            if (hdr.sr.path_len > 4 || hdr.sr.current_index >= hdr.sr.path_len) {
                mark_to_drop(standard_metadata);
                hdr.sr.setInvalid();
            } else {
                sr_table.apply();
                // 完成转发后清除头部
                if (hdr.sr.current_index >= hdr.sr.path_len) {
                    hdr.sr.setInvalid();
                }
            }
        } else {
            mark_to_drop(standard_metadata);
        }
    }
}

/*************************************************************************
******************* EGRESS PROCESSING ************************************
*************************************************************************/

control MyEgress(inout headers hdr,
                 inout metadata meta,
                 inout standard_metadata_t standard_metadata) {
    apply { }
}

/*************************************************************************
******************* CHECKSUM COMPUTATION **********************************
*************************************************************************/

control MyComputeChecksum(inout headers hdr, inout metadata meta) {
    apply {
        update_checksum(
            hdr.ipv4.isValid(),
            {
                hdr.ipv4.version,
                hdr.ipv4.ihl,
                hdr.ipv4.diffserv,
                hdr.ipv4.totalLen,
                hdr.ipv4.identification,
                hdr.ipv4.flags,
                hdr.ipv4.fragOffset,
                hdr.ipv4.ttl,
                hdr.ipv4.protocol,
                hdr.ipv4.srcAddr,
                hdr.ipv4.dstAddr
            },
            hdr.ipv4.hdrChecksum,
            HashAlgorithm.csum16
        );
    }
}

/*************************************************************************
************************ DEPARSER ****************************************
*************************************************************************/

control MyDeparser(packet_out pkt, in headers hdr) {
    apply {
        pkt.emit(hdr.ethernet);
        pkt.emit(hdr.ipv4);
        pkt.emit(hdr.ipv6);
        pkt.emit(hdr.sr);
    }
}

/*************************************************************************
************************** SWITCH ****************************************
*************************************************************************/

V1Switch(
    MyParser(),
    MyVerifyChecksum(),
    MyIngress(),
    MyEgress(),
    MyComputeChecksum(),
    MyDeparser()
) main;
